package com.example.gray.utils;

import com.example.gray.entity.LogList;
import com.example.gray.entity.OpLog;
import com.example.gray.entity.Result;
import com.example.gray.service.OpLogService;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Gray 2022/1/5-10:37
 */
@Aspect
@Component
@Order(3)
public class MyAspect {
    @Autowired
    OpLogService service;

    @Around("@annotation(com.example.gray.utils.LogAnno)")
    public Object run(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest();
        String ip = request.getHeader("x-forwarder-for");
        if (ip == null){ip = "127.0.0.1";}
        Object[] args = pjp.getArgs();
        OpLog log = new OpLog();
        log.setIpAddress(ip);
        boolean status = false;
        for (Object o :
                args) {
            if (status){
                log.setOpMethods(o.toString());
            }else {
                log.setUserId(Integer.parseInt(o.toString()));
                status = true;
            }
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        log.setOpDate(dateFormat.format(date));
        System.out.println(log);
        try {
            service.insert(log);
            return Result.success("插入成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(4002,"插入失败","");
        }
    }

}
